//
//  DHDataBaseOperate.swift
//  FootballDataRecord
//
//  Created by sea on 2020/1/8.
//  Copyright © 2020 Xx Jiang. All rights reserved.
//

import UIKit


enum SQLType {
    case insert
    case change
    case delete
    case search
}
/// 数据库相关操作
class DHDataBaseOperate: NSObject {
    
    class func insertModelToDB(model:AnyObject,ComeleteBlock:@escaping compeletBlock){
        
        let poprtyList:[String] = getAllPropertys(anymodel: model)
        
        var sqlString = getSqlHeader(model: model,sqlType: SQLType.insert)
        
        var sqlTailString = " values("
        
        var valueArr = [String]()
        var i = 0;
        
        //通过属性方法列表获取属性的字符串 通过字符串 key-value获取值
        var valueKeyArr = [[String:String]]()
        for propertyName in poprtyList {
            let value  = model.value(forKey: propertyName)
            if value != nil && value is String {
                let dic = ["propertyName":propertyName as String ,"value":value as! String]
                valueKeyArr.append(dic)
            }
        }
        
        for dict in valueKeyArr {
            var valueString:String?
            valueString = (dict["value"]!)
            valueArr.append(valueString!)
            if i == 0 {
                sqlString.append(dict["propertyName"]!)
                sqlTailString.append("?")
            }else{
                sqlString.append(",\(dict["propertyName"]!)")
                sqlTailString.append(",?")
            }
            if i == valueKeyArr.count - 1 {
                sqlString.append(")")
                sqlTailString.append(")")
                sqlString.append(" \(sqlTailString)")
            }
            i += 1
        }
        
        print(sqlString)
        print(valueArr)
        
        DHDataBaseManager.shareDataBaseManager.inserObjcWithSql(sql: sqlString, valueArr: valueArr, CompeletBlock: ComeleteBlock)
    }
    
    /// 数据库改
    /// - Parameters:
    ///   - model: 模型对象
    ///   - keys: 需要修改数据的键， mainkey 主键 valuekey 修改值的键（注：keys["valueKey"] 的值只有两种类型：1 String 2 [String]）
    ///   - ComeleteBlock: 完成回调
    
    class func changeValuesWithModel(model:AnyObject,keys:[String:Any],ComeleteBlock:@escaping compeletBlock){
        
        var sqlString = getSqlHeader(model: model, sqlType: SQLType.change)
        
        let keyValue = model.value(forKey: keys["mainKey"] as! String)
        
        if keyValue == nil {
            print("model 主键值为空")
            return
        }
        if keys["valueKey"] is String {
            let value:String? = (model.value(forKey: keys["valueKey"] as! String) as! String)
            if value != nil {
                sqlString = "\(sqlString) set \(keys["valueKey"] as! String) = '\(value ?? "")' where \(keys["mainKey"] as! String) = '\(keyValue as! String)'"
            }else{
                print("model 值为空")
                return
            }
        }else{
            let valueKeys:[String] = keys["valueKey"] as! [String]
            var i = 0
            for key in valueKeys {
                let modelValue = model.value(forKey: key)
                
                if i == 0 {
                    if modelValue is String {
                        let newValue = modelValue as! String
                      sqlString = "\(sqlString) set \(key) = '\(newValue)'"
                    }else if modelValue is Int{
                        let newValue = modelValue as! Int
                        sqlString = "\(sqlString) set \(key) = \(NSNumber.init(value:newValue))"
                    }
                    
                }else{
                    if modelValue is String {
                        let newValue = modelValue as! String
                        sqlString = "\(sqlString),\(key) = '\(newValue)'"
                    }else{
                        let newValue = modelValue as! Int
                        sqlString = "\(sqlString),\(key) = \(NSNumber.init(value: newValue))"
                    }
                    
                }
                if i == valueKeys.count - 1{
                    sqlString = "\(sqlString) where \(keys["mainKey"] as! String) = '\(keyValue as! String)'"
                    
                }
                i += 1
            }
        }
        DHDataBaseManager.shareDataBaseManager.doSomethingWithSql(sql: sqlString, valueArr: [], CompeletBlock: ComeleteBlock)
    }
    
    
    class func deleteModelValueFromDB(model:AnyObject,mainKey:String,ComeleteBlock:@escaping compeletBlock) {
        var sqlString = getSqlHeader(model: model, sqlType: .delete)
        
        
        sqlString = "\(sqlString) where \(mainKey) = '\(model.value(forKey: mainKey) as! String)'"
        
        
        DHDataBaseManager.shareDataBaseManager.doSomethingWithSql(sql: sqlString, valueArr: [], CompeletBlock: ComeleteBlock)
    }
    
    
    
    class func searchDatasFromDB(sqlString:String,ComeleteBlock:@escaping compeletBlock){
        DHDataBaseManager.shareDataBaseManager.searchWithSql(sql: sqlString, CompeletBlock: ComeleteBlock)
    }
    
    
    private  class func getSqlHeader(model:AnyObject,sqlType:SQLType)->(String){
        var sqlString:String = ""
        
        var sqlBody:String = ""
        switch model {
        case is TeamModel:
            sqlBody.append(" \(teamTableName)")
            break
        case is PlayerModel:
            sqlBody.append(" \(playerTableName)")
            break
        case is MatchDataModel:
            sqlBody.append(" \(matchDataTableName)")
            break
        default:
            sqlBody.append(" \(matchTableName)")
            break
        }
        var sqlHeader:String?
        switch sqlType {
        case .insert:
            sqlHeader  = "insert into"
            sqlString = "\(sqlHeader!) \(sqlBody) ("
        case .change:
            sqlHeader = "update"
            sqlString = "\(sqlHeader!) \(sqlBody)"
        case .delete:
            sqlHeader = "delete from"
            sqlString = "\(sqlHeader!) \(sqlBody)"
        default:
            sqlHeader = "search * from"
            sqlString = "\(sqlHeader!) \(sqlBody)"
        }
        return sqlString
    }
    
    
    class func getAllPropertys(anymodel:AnyObject) -> [String] {
        var  result  = [String]()
        
        var count:UInt32 = 0
        let list = class_copyPropertyList(anymodel.self.classForCoder, &count)
        
        for i in 0..<Int(count){
            let property = list?[i]
            let cName = property_getName(property!)
            let name = String(utf8String: cName)
            result.append(name!)
        }
        return result
    }
    
}
